package com.sqj.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

/**
 * @author sqj88
 * @date 2018/6/21 11:44
 */
public class DiscardServer {
    private int port;

    public DiscardServer(int port) {
        super();
        this.port = port;
    }

    public void run() throws Exception{
        //bossGroup接收进来的连接
        EventLoopGroup bossGroup=new NioEventLoopGroup();
        //workerGroup处理接收进来的连接
        //EventLoopGroup workerGroup=new NioEventLoopGroup();
        System.out.println("准备运行端口："+port);
        //serverBootstrap是Nio服务辅助启动类
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup);
            //serverBootstrap.group(bossGroup,workerGroup);
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.localAddress(new InetSocketAddress(port));
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new DiscardServerHandler());
                }
            });
            serverBootstrap.option(ChannelOption.SO_BACKLOG,128);
            serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE,true);
            ChannelFuture sync = serverBootstrap.bind().sync();
            System.out.println(sync.channel().localAddress());
            sync.channel().closeFuture().sync();
        }finally {
           // workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}
